<script setup>
import { ref, reactive } from "vue";
import { getRoleList, delRole } from "@/api/role";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import Pagination from "@/components/Pagination/index.vue";

const router = useRouter();
const loading = ref(false);
const roleList = ref([]);
const searchForm = reactive({
  name: "",
  page: 1,
});

getRoleListData();
async function getRoleListData(type) {
  loading.value = true;
  let res;
  if (type == "search") {
    res = await getRoleList(searchForm);
  } else {
    res = await getRoleList();
  }
  loading.value = false;
  roleList.value = res.data;
}
async function addRoleFn() {
  router.push({
    path: "/role/addrole",
  });
}
async function editRoleFn(row) {
  router.push({
    path: "/role/addrole",
    query: {
      id: row.id,
    },
  });
}
async function delRoleFn(row) {
  const res = await delRole({ id: row.id });
  if (res.code == 200) {
    ElMessage.success("删除成功");
    getRoleListData();
  }
}
function changePagination(e) {
  searchForm.page = e.page;
  getRoleListData();
}
</script>

<template>
  <div class="container">
    <p class="title">权限组管理</p>
    <div class="box mb-2">
      <div class="search">
        <div class="cell">
          <span>账号：</span>
          <el-input style="width: 150px" v-model="searchForm.name" />
        </div>
        <div class="cell">
          <el-button :loading="loading" type="primary" @click="getRoleListData('search')"
            >查询</el-button
          >
          <el-button>重置</el-button>
          <el-button @click="addRoleFn" class="mr-1" type="primary">添加账号</el-button>
        </div>
      </div>
    </div>
    <div class="box">
      <el-table v-loading="loading" border :data="roleList.data" style="width: 100%">
        <el-table-column label="ID" width="120">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column prop="name" label="角色名称" width="120" />
        <el-table-column prop="created_at" label="发布时间" />
        <el-table-column fixed="right" prop="status" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" @click="editRoleFn(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除?" @confirm="delRoleFn(scope.row)">
              <template #reference>
                <el-button type="warning">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        @pagination="changePagination"
        :total="roleList.total"
        :page="searchForm.page"
      />
    </div>
  </div>
</template>
<style scoped>
.search {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.cell {
  display: flex;
  align-items: center;
  margin-right: 10px;
  span {
    white-space: nowrap;
    transform: translateY(-2px);
  }
}
</style>
